﻿namespace LeetCodeProject._3001_4000._3240;

// 3240. 最少翻转次数使二进制矩阵回文 II
public class Solution
{
    public int MinFlips(int[][] grid)
    {
        int m = grid.Length, n = grid[0].Length, ans = 0;
        int cnt1 = 0;
        for (int i = 0; i < m / 2; i++)
        {
            for (int j = 0; j < n / 2; j++)
            {
                cnt1 = grid[i][j] + grid[i][n - 1 - j] +
                       grid[m - 1 - i][j] + grid[m - 1 - i][n - 1 - j];
                ans += Math.Min(cnt1, 4 - cnt1);
            }
        }

        int diff = 0;
        cnt1 = 0;
        if (m % 2 == 1)
        {
            for (int j = 0; j < n / 2; j++)
            {
                if ((grid[m / 2][j] ^ grid[m / 2][n - 1 - j]) != 0)
                {
                    diff++;
                }
                else
                {
                    cnt1 += grid[m / 2][j] * 2;
                }
            }
        }

        if (n % 2 == 1)
        {
            for (int i = 0; i < m / 2; i++)
            {
                if ((grid[i][n / 2] ^ grid[m - 1 - i][n / 2]) != 0)
                {
                    diff++;
                }
                else
                {
                    cnt1 += grid[i][n / 2] * 2;
                }
            }
        }

        if (m % 2 == 1 && n % 2 == 1)
        {
            ans += grid[m / 2][n / 2];
        }

        if (diff > 0)
        {
            ans += diff;
        }
        else
        {
            ans += cnt1 % 4;
        }

        return ans;
    }
}